package com.rgs.nginx.exption;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Classname GlobalExceptionHandler
 * @Description TODO
 * @Date 2025/2/13 15:28
 * @Created by rgs
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final String TRACE_ID = "traceId";

    @ExceptionHandler()
    public ResponseData<String> defaultErrorHandler(Exception e) {
        log.info("全局捕获异常执行");
        log.error("捕获业务异常：", e);
        if (e instanceof ServiceException) {
            ServiceException serviceException = (ServiceException) e;
            if (ExceptionEnum.COMMON_ERROR.getCode().equals(serviceException.getErrCode())) {
                if (serviceException.getMessage().equals(ExceptionEnum.COMMON_ERROR.getMessage())) {
                    return new ResponseData<>(serviceException.getErrCode(), serviceException.getMessage() + "。参考日志:" + MDC.get(TRACE_ID));
                }
                return new ResponseData<>(serviceException.getErrCode(), serviceException.getMessage());
            }
            return new ResponseData<>(serviceException.getErrCode(), e.getMessage());
        }
        return new ResponseData<>(ExceptionEnum.FAILURE.getCode(), e.getCause().getMessage() + "。参考日志:" + MDC.get(TRACE_ID));
    }
}
